﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;

public partial class Admin_Components_MasterData_CustomerPopup : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Session["UserName"] == null)
            {
                Response.Redirect("~/Default.aspx", true);
            }
            Utils.loadLocation(cboProvince, 0, 1, 1);
            Utils.loadLocation(cboDistrict, int.Parse(cboProvince.SelectedValue), 1, 2);
            gv.DataSource = new DataTable();
            gv.DataBind();
        }
    }

    protected void gvData_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
    {
        Loaddata();

    }


    private void Loaddata()
    {
        DBDataContext db = LINQUtil.GetDBWriteOnly();

        String CustomerCode = Utils.KillChars(this.txtCustomerCode.Text.Trim());
        String CustomerName = Utils.KillChars(this.txtCustomerName.Text.Trim());
        String CustomerPhone = Utils.KillChars(this.txtPhoneNumber.Text.Trim());
        int PageNumber = gv.CurrentPageIndex + 1;
        int PageSize = gv.PageSize;

        var q = db.Customer_Search(CustomerCode, CustomerName, CustomerPhone, "", 0, 0, PageSize, PageNumber).ToList();
        if (q.Count > 0)
        {
            gv.ClientSettings.Scrolling.UseStaticHeaders = true;
            gv.VirtualItemCount = q[0].TotalRows.Value;
            gv.DataSource = q;
        }
        /*
        else
        {
            gv.DataSource = new DataTable();
        }
         * */
       
    }


    protected void btnSave_Click(object sender, EventArgs e)
    {
        try
        {
            DBDataContext dbread = LINQUtil.GetDBWriteOnly();
            Customer customer = new Customer();

            // String CustomerCode = Utils.KillChars(this.txtCustomerCode.Text.Trim());
            String CustomerName = Utils.KillChars(this.txtCustomerName.Text.Trim());
            String CustomerPhone = Utils.KillChars(this.txtPhoneNumber.Text.Trim());
            String Email = Utils.KillChars(this.txtEmail.Text.Trim());
            String Address = Utils.KillChars(this.txtAddress.Text.Trim());
            int DistrictID = Convert.ToInt32(this.cboDistrict.SelectedValue == "" ? "0" : this.cboDistrict.SelectedValue);
            int ProvinceID = Convert.ToInt32(this.cboProvince.SelectedValue == "" ? "0" : this.cboProvince.SelectedValue);
            
            //Check khong cho phep trung do dien thoai
            var check = (from cus in dbread.Customers
                         where cus.PhoneNumber == CustomerPhone
                         select cus).FirstOrDefault();
            if (check != null)
            {
                JavascriptUtil.LoadMessage(UpdatePanel1, false, "Số điện thoại: " + CustomerPhone+" đã tồn tại. vui lòng chọn số khác");
                return;
            }

            //Lay ma sau cung
            int lenZero = 7;//So ky tu khôg tính chữ cái đưungs đầu. ví dụ KH0000001 --> 7, k tính KH
            var customerCodeMax = dbread.Customers.Max(d => d.OrderNumber);
            int MaxOrderNumber = (customerCodeMax == null ? 0 : Convert.ToInt32(customerCodeMax)) + 1;
            String LastCode = ("000000" + MaxOrderNumber).ToString();
            String CustomerCode = "KH" + LastCode.Substring(LastCode.Length - lenZero);
            //End

            customer.CustomerCode = CustomerCode;
            customer.CustomerName = CustomerName;
            customer.PhoneNumber = CustomerPhone;
            customer.Email = Email;
            customer.Address = Address;
            customer.DistrictID = DistrictID;
            customer.ProvinceID = ProvinceID;
            customer.AccumulateAmount = 0;
            customer.ConvertedAmount = 0;
            customer.RemainAmount = 0;
            customer.CreatedBy = Session["UserName"].ToString();
            customer.CreatedDateTime = DateTime.Now;
            customer.LastUpdatedBy = Session["UserName"].ToString();
            customer.LastUpdatedDateTime = DateTime.Now;
            customer.Status = 'A';
            customer.OrderNumber = MaxOrderNumber;
            dbread.Insert<Customer>(customer);
            dbread.SubmitChanges();

            String DistrictName = cboDistrict.SelectedItem.Text;
            String ProvinceName = cboProvince.SelectedItem.Text;
            string AddressFull = Address + ", " + DistrictName + ", " + ProvinceName;
            this.txtCustomerCode.Text = CustomerCode;
            Session["Cus"] = CustomerCode+"@"+CustomerName;
           // JavascriptUtil.LoadMessage(UpdatePanel1, true, "Lưu thành công!");
           // ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "ClientClose", "ClientClose();", true);
            ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "ClientClose2", "ClientClose2('" + CustomerCode + "','" + CustomerName + "','" + CustomerPhone + "','" + AddressFull + "');", true);
        }catch(Exception ex){

        }
    }
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        Loaddata();
        gv.DataBind();
    }

    protected void lnkCustomerCode_Click(object sender, EventArgs e)
    {
        LinkButton LNKCustomer = (LinkButton)sender;
        GridDataItem dataItem = (GridDataItem)LNKCustomer.NamingContainer;
        String CustomerName = dataItem["CustomerName"].Text;
        String CustomerCode = LNKCustomer.Text;
        String CustomerPhone = dataItem["PhoneNumber"].Text;
        String AddressFull = dataItem["Address"].Text + ", " + dataItem["District"].Text + ", " + dataItem["Province"].Text;
 
        Session["Cus"] = CustomerCode + "@" + CustomerName;
       // ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "ClientClose2", "ClientClose2('" + CustomerCode + "','" + CustomerName + "');", true);
        ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "ClientClose2", "ClientClose2('" + CustomerCode + "','" + CustomerName + "','" + CustomerPhone + "','" + AddressFull + "');", true);
    }

    protected void lnkCustomerCode_Click_bk(object sender, EventArgs e)
    {
        /*
        <asp:HyperLink ID="lnkCustomerCode" runat="server" Text='<%# Eval("CustomerCode") %>' style="cursor:pointer;text-decoration:underline;" 
            onclick='<%# string.Format("javascript:return ClientClose2(\"{0}\",\"{1}\")", Eval("CustomerCode"),Eval("CustomerName")) %>'></asp:HyperLink>
        */

        HyperLink LNKCustomer = (HyperLink)sender;
        GridDataItem dataItem = (GridDataItem)LNKCustomer.NamingContainer;
        String CustomerName = dataItem["CustomerName"].Text;
        String CustomerCode = dataItem["CustomerCode"].Text;
        Session["Cus"] = CustomerCode + "@" + CustomerName;
        ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "ClientClose", "ClientClose();", true);
    }

    protected void cboProvince_SelectedIndexChanged(object sender, EventArgs e)
    {
        string provinceID = cboProvince.SelectedValue;
        Utils.loadLocation(cboDistrict, int.Parse(provinceID), 0, 0);
    }
}